package com.opencee.boot.autoconfigure.db.mybatis.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opencee.boot.autoconfigure.db.mybatis.mapper.SuperMapper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;

/**
 * @author liuyadu
 */
public class SupperServiceImpl<M extends SuperMapper<T>, T> extends ServiceImpl<M, T> {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveBatch(Collection<T> entityList, int batchSize) {
        return this.executeBatchPartition(entityList, batchSize, (sqlSession, list) -> {
            this.baseMapper.insertBatch(list);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveBatch(Collection<T> entityList) {
        return saveBatch(entityList, 200);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateBatchById(Collection<T> entityList) {
        return updateBatchById(entityList, 200);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateBatchById(Collection<T> entityList, int batchSize) {
        return this.executeBatchPartition(entityList, batchSize, (sqlSession, list) -> {
            this.baseMapper.updateBatch(list);
        });
    }

    protected <E> boolean executeBatchPartition(Collection<E> list, int batchSize, BiConsumer<SqlSession, Collection<E>> consumer) {
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        // 集合分片
        List<List<E>> newList = ListUtil.partition(new ArrayList<>(list), batchSize);
        // 打印分片集合
        return this.executeBatch((sqlSession) -> {
            newList.forEach(t -> {
                consumer.accept(sqlSession, t);
                sqlSession.flushStatements();
            });
        });
    }

}